package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import cn.com.kh.signUtil
import com.alibaba.fastjson.JSONArray
import net.sf.json.JSONObject
import com.alibaba.fastjson.parser.Feature
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import sun.misc.BASE64Encoder

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.lang.reflect.Array
import java.text.SimpleDateFormat

/**
 * 创建法大大合同接口
 */

public class apiCreateContractold implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiCreateContractold.class);
    private static String APPKEY;
    private static String APPID;
    private static String URL;
    private String charset = "utf-8"; // 设置字符集
    private int timeout = 100000; // 设置请求超时时间
    private int enableSSLflag = 0;
    private String LOCALURL = "";
    private String CALLBACKURL = "";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        String v_interfacetype = request.getParameter("interfacetype");

        // 初始化返回参数
        JSONObject results = new JSONObject();

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);

        try {
            JSONObject inJson = JSONObject.fromObject(callJson);

            LOCALURL = KHDBConfig.getAPIURL(eliteBean, "Groovy-Inner");
            URL = KHDBConfig.getAPIURL(eliteBean, "fddurl");
            CALLBACKURL = KHDBConfig.getAPIURL(eliteBean, "callbackip");

            APPKEY = KHDBConfig.getParam(eliteBean, "FDDKEY");
            APPID = KHDBConfig.getParam(eliteBean, "FDDID");

            if (v_interfacetype == "create") {
                //获取工单id
                String workroderid = inJson.getString("contractid");
                //获取客户编号
                String customerID = inJson.getString("customerID");
                //获取客户类型
                String customertype = inJson.getString("customerType");//1,客户 2.企业
                //获取合同模板id
                String ModelID = inJson.getString("ModelID");
                //获取甲方
                String PartyA = inJson.getString("PartyA");
                //获取填充参数
                JSONObject assembly = inJson.getJSONObject("data");
                getAssembly(ModelID);

                List<Object> assList = new ArrayList();
                JSONObject assemblyPara = new JSONObject();
                Iterator<String> keys = assembly.keys();
                while (keys.hasNext()) {
                    String teams = keys.next();
                    log.debug("teams: " + teams);
                    assemblyPara.put("name", teams);
                    assemblyPara.put("value", assembly.getString(teams));
                    log.debug("assemblyPara:" + assemblyPara);
                    assList.add(assemblyPara.toString());
                    assemblyPara.clear();
                }
                log.debug("assList:" + assList.toString());

                JSONObject fillContracts = fillContract(assList, ModelID, workroderid, customerID);
                if (fillContracts.getString("code") != "1") {
                    results = fillContracts;
                } else {
                    results.put("code", "1");
                    results.put("msg", "合同生成成功");
                }

            } else if (v_interfacetype == "push") { //推送签署
			//--------------------------
			
                //获取工单id
                String workroderid2 = inJson.getString("workroderid");
                //获取客户编号
                String customerID = inJson.getString("customerID");
                //获取第几位
                String nums = inJson.getString("nums");
                //获取客户类型
                String customertype = inJson.getString("customerType");//1,客户 2.企业
				
				//根据工单id查询生成合同编号
			    List hjx_businessnumber = eliteBean.chaxun_sql("select contractid from fdd_agreement_list where workroderid='"+workroderid2+"'", "dataSource");
				if (hjx_businessnumber.size() > 0) {//循环遍历
                int arrInt = hjx_businessnumber.size();
                log.debug(arrInt);
                for (int h = 0; h < arrInt; h++) {
					String workroderid = hjx_businessnumber.get(h).get("contractid");
					log.debug("workroderid:"+workroderid);
					
				    JSONObject pushCustomers = pushCustomer(workroderid, customerID, customertype);
					log.debug("推送客户:" + pushCustomers);
					
					if (pushCustomers.getString("code") != "1") {
						results = pushCustomers;
					} else {

						if (nums == "1") {
							JSONObject resultss = pushAdmin(workroderid, eliteBean);
							log.debug("推送印章管理员:" + resultss);
							if (resultss.getString("code") != "1") {
								results = resultss;
							} else {
								String[] custTaskDealSQL = new String[1];
							    custTaskDealSQL[0] = "UPDATE fdd_agreement_list SET pushsigning = '已推送',pushsigningtime=now() WHERE contractid = '"+workroderid+"'"
							    int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
                                log.debug("SQL返回结果：" + batchSQLResult.toString());
								
								results.put("code", "1");
								results.put("msg", "合同推送完成（含印章管理员）");	
								
							}
						} else {
							String[] custTaskDealSQL = new String[1];
							custTaskDealSQL[0] = "UPDATE fdd_agreement_list SET pushsigning = '已推送',pushsigningtime=now() WHERE contractid = '"+workroderid+"'"
							int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
                            log.debug("SQL返回结果：" + batchSQLResult.toString());
							
							results.put("code", "1");
							results.put("msg", "合同推送完成（不含印章管理员）");
						}
					}
					
				   }
				}
				
            } else {
                results.put("code", "-1");
                results.put("msg", "interfacetype类型不存在");
            }

        } catch (Exception e) {
            results.put("code", 1008);
            results.put("msg", e.getMessage());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "内部合同创建调用-P2", "apiCreateContract", callJson, results.toString(), (System.currentTimeMillis() - startTime).toString(), v_interfacetype);
        }
        return results.toString();
    }

    //推送门户签署(印章管理员)
    public JSONObject pushAdmin(String workorderid, EliteBean eliteBean) {
        JSONObject jsonPara = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");

        def fdd_list = eliteBean.chaxun_sql("select customerid,companyCustomerid from fdd_admin", "dataSource");
        if (fdd_list) {
            String fddcustomerid = fdd_list[0].get("customerid");
            String companyCustomerid = fdd_list[0].get("companyCustomerid");
            jsonPara.put("customerId", fddcustomerid);
            jsonPara.put("companyCustomerId", companyCustomerid);
            jsonPara.put("docNo", workorderid);
            jsonPara.put("autoArchive", "1");
            jsonPara.put("transactionNo", System.currentTimeMillis() / 1000);
            jsonPara.put("notifyUrl", CALLBACKURL + "/api/apiContractCallback");
            jsonPara.put("companyKeyWord", "甲方盖章处");
            jsonPara.put("companyKeywordStrategy", 0);

            JSONObject jsondatePara = new JSONObject();
            jsondatePara.put("keyword", "甲方签章日期");
            jsondatePara.put("keywordStrategy", 0);
            jsonPara.put("dateSealKeywordDTO", jsondatePara);

            String bizContent = getbizContent(jsonPara.toString());
            bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;
            JSONObject jsons = new JSONObject();
            String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            jsons.put("timestamp", datetime);
            jsons.put("bizContent", bizContent);
            jsons.put("signType", "SHA256");
            jsons.put("appId", APPID);
            String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
            signString = signString.replace("\\n", "");

            String signstr1 = Util.getSHA256Str(signString).toUpperCase();
            String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
            String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
            jsons.put("sign", sign);
            log.debug("推送门户签署参数:" + jsons.toString().replace("\\n", ""));
            String Assemblys = Util.doHttpPostUseHead(URL + "/sign/portal-url/push", jsons.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);
            JSONObject obj = JSONObject.fromObject(Assemblys);
            return obj;
        } else {
            JSONObject obj = new JSONObject();
            obj.put("code", -1);
            obj.put("msg", "未获取到印章管理员信息");
            return obj;
        }
    }

    //推送门户签署
    public JSONObject pushCustomer(String workorderid, String customerID, String customertype) {
        JSONObject jsonPara = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        if (customertype == "1") {
            jsonPara.put("customerId", customerID);
        } else if (customertype == "2") {
            jsonPara.put("companyCustomerId", customerID);
        }
        jsonPara.put("docNo", workorderid);
        jsonPara.put("autoArchive", "2");
        jsonPara.put("transactionNo", System.currentTimeMillis() / 1000);
        jsonPara.put("notifyUrl", CALLBACKURL + "/api/apiContractAdminCallback");
        jsonPara.put("personKeyWord", "乙方盖章处");
        jsonPara.put("personKeywordStrategy", 0);

        JSONObject jsondatePara = new JSONObject();
        jsondatePara.put("keyword", "乙方签章日期");
        jsondatePara.put("keywordStrategy", 0);
        jsonPara.put("dateSealKeywordDTO", jsondatePara);

        String bizContent = getbizContent(jsonPara.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;
        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");
        log.debug("signString:" + signString);
        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        jsons.put("sign", sign);
        log.debug("推送门户签署参数:" + jsons.toString().replace("\\n", ""));
        String Assemblys = Util.doHttpPostUseHead(URL + "/sign/portal-url/push", jsons.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);
        JSONObject obj = JSONObject.fromObject(Assemblys);
        return obj;
    }

    //编辑模板填充
    public JSONObject fillContract(List assList, String ModelID, String workorderid, String customerID) {
        JSONObject jsonPara = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        jsonPara.put("id", ModelID);
        jsonPara.put("contractTitle", "合同签署");
        jsonPara.put("contractNo", workorderid);
        //jsonPara.put("personCustomerId","a59cdbf03fbd4f47a358814c1a574d10");
        //jsonPara.put("companyCustomerid","36d29f1c90c143c7a29f2b672936fad9");
		jsonPara.put("personCustomerId","");
        jsonPara.put("companyCustomerId", "36d29f1c90c143c7a29f2b672936fad9");//personCustomerId
        jsonPara.put("onlineWidgetDetailDTOS", assList);
        jsonPara.put("crossPlatform", 1);//因法大大改版新增
        String bizContent = getbizContent(jsonPara.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;

        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");

        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        jsons.put("sign", sign);
        log.debug("编辑模板填充参数:" + jsons.toString().replace("\\n", ""));

        String Assemblys = Util.doHttpPostUseHead(URL + "/online-template/fill", jsons.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);

        JSONObject obj = JSONObject.fromObject(Assemblys);
        return obj;
    }

    //获取合同模板控件
    public JSONObject getAssembly(String Modelid) {
        JSONObject jsonPara = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");

        jsonPara.put("id", Modelid);
        String bizContent = getbizContent(jsonPara.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", "");

        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");
        log.debug("signString:" + signString);
        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        log.debug("signstr1:" + signstr1);
        log.debug("signstr1:" + signstr1 + APPKEY);
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        log.debug("signstr2:" + signstr2);
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        jsons.put("sign", sign);
        log.debug("合同模板控件参数:" + jsons.toString().replace("\\n", ""));
        String Assemblys = Util.doHttpPostUseHead(URL + "/online-template/widget/list", jsons.toString().replace("\\n", ""), null, timeout, enableSSLflag, headMap);
        log.debug("Assemblys:" + Assemblys)
        JSONObject obj = JSONObject.fromObject(Assemblys);
        return obj;
    }

    //获取bizContent
    public String getbizContent(String param) {
        log.debug("param:" + param);
        String encodedObject = URLEncoder.encode(param, "UTF-8");
        String biz_contents = new BASE64Encoder().encodeBuffer(encodedObject.getBytes("UTF-8"));
        log.info("[biz_contents]:" + biz_contents);
        return biz_contents;
    }
}